<template>
  <div>
    <!-- 星期选择按钮 -->
    <div style="margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px;">
      <el-button type="success" @click="selectAll">全部</el-button>
      <el-button
          v-for="weekday in weekdays"
          :key="weekday.value"
          :type="selectedWeekday === weekday.value ? 'primary' : 'default'"
          @click="selectWeekday(weekday.value)"
          style="width: 100px; text-align: center"
      >
        {{ weekday.label }}
      </el-button>
    </div>

    <!-- 查询 -->
    <div style="margin-bottom: 20px;">
      <el-input
          placeholder="请输入膳食名称"
          style="width:200px"
          v-model="queryFoodName"
      ></el-input>
      <el-button @click="queryByFoodName" type="success" plain>查询</el-button>
      <el-button
          @click="showFoodDialog"
          type="primary"
          style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px"
      >
        登&emsp;记
      </el-button>
    </div>

    <!-- 显示所有膳食信息（列表视图） -->
    <div v-if="showList">
      <div>{{errorMessage}}</div>
      <el-table :data="foodList">
        <el-table-column label="序号" type="index" width="60px"></el-table-column>
        <el-table-column prop="foodId" label="ID" width="60px"></el-table-column>
        <el-table-column prop="foodname" label="膳食名称" width="100px"></el-table-column>
        <el-table-column prop="foodtype" label="膳食类别" width="100px"></el-table-column>
        <el-table-column prop="foodlabel" label="膳食标签" width="100px"></el-table-column>
        <el-table-column prop="foodprice" label="膳食价格" width="100px"></el-table-column>
        <el-table-column prop="isMuslim" label="是否清真" width="70px">
          <template #default="scope">
            {{scope.row.isMuslim === '0' ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column prop="supplyDate" label="供应星期" width="100px"></el-table-column>
        <el-table-column prop="supplyType" label="供应类型" width="100px">
          <template #default="scope">
            {{scope.row.supplyType === '1' ? '早餐' : scope.row.supplyType === '2' ? '午餐' : '晚餐'}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="showEditDialog(scope.row.foodId)">修改</el-button>
            <el-button type="danger" @click="removeOne(scope.row.foodId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="example-pagination-block">
        <el-pagination background
                       v-model:current-page="pageContains.pageNum"
                       v-model:page-size="pageContains.pageSize"
                       :page-sizes="[10,20,30,50,100]"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="pageContains.total"
                       @size-change="handleSizeChange"
                       @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 膳食信息分类显示（卡片视图） -->
    <div v-else>
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <h3>早餐</h3>
          <div v-for="(food, index) in morningFoods" :key="food.foodId" style="margin-bottom: 10px;">
            <el-card class="box-card">
              <div style="display: flex; justify-content: space-between;">
                <div>
                  <p><strong>{{ food.foodname }}</strong></p>
                  <p>类别: {{ food.foodtype }}</p>
                  <p>价格: {{ food.foodprice }}元</p>
                  <p>清真: {{ food.isMuslim === '0' ? '是' : '否' }}</p>
                </div>
                <div style="display: flex; gap: 10px;">
                  <el-button type="primary" size="small" @click="showEditDialog(food.foodId)">修改</el-button>
                  <el-button type="danger" size="small" @click="removeOne(food.foodId)">删除</el-button>
                </div>
              </div>
            </el-card>
          </div>
          <el-card v-if="morningFoods.length < 8" class="box-card" style="margin-top: 10px;">
            <div style="display: flex; justify-content: center; align-items: center; height: 100px;">
              <el-button type="primary" @click="addMorningFood">新增早餐</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <h3>午餐</h3>
          <div v-for="(food, index) in noonFoods" :key="food.foodId" style="margin-bottom: 10px;">
            <el-card class="box-card">
              <div style="display: flex; justify-content: space-between;">
                <div>
                  <p><strong>{{ food.foodname }}</strong></p>
                  <p>类别: {{ food.foodtype }}</p>
                  <p>价格: {{ food.foodprice }}元</p>
                  <p>清真: {{ food.isMuslim === '0' ? '是' : '否' }}</p>
                </div>
                <div style="display: flex; gap: 10px;">
                  <el-button type="primary" size="small" @click="showEditDialog(food.foodId)">修改</el-button>
                  <el-button type="danger" size="small" @click="removeOne(food.foodId)">删除</el-button>
                </div>
              </div>
            </el-card>
          </div>
          <el-card v-if="noonFoods.length < 8" class="box-card" style="margin-top: 10px;">
            <div style="display: flex; justify-content: center; align-items: center; height: 100px;">
              <el-button type="primary" @click="addNoonFood">新增午餐</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <h3>晚餐</h3>
          <div v-for="(food, index) in eveningFoods" :key="food.foodId" style="margin-bottom: 10px;">
            <el-card class="box-card">
              <div style="display: flex; justify-content: space-between;">
                <div>
                  <p><strong>{{ food.foodname }}</strong></p>
                  <p>类别: {{ food.foodtype }}</p>
                  <p>价格: {{ food.foodprice }}元</p>
                  <p>清真: {{ food.isMuslim === '0' ? '是' : '否' }}</p>
                </div>
                <div style="display: flex; gap: 10px;">
                  <el-button type="primary" size="small" @click="showEditDialog(food.foodId)">修改</el-button>
                  <el-button type="danger" size="small" @click="removeOne(food.foodId)">删除</el-button>
                </div>
              </div>
            </el-card>
          </div>
          <el-card v-if="eveningFoods.length < 8" class="box-card" style="margin-top: 10px;">
            <div style="display: flex; justify-content: center; align-items: center; height: 100px;">
              <el-button type="primary" @click="addEveningFood">新增晚餐</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 膳食信息对话框 -->
    <el-dialog v-model="foodDialog" :title="dialogTitle">
      <el-form :model="curFood">
        <el-form-item label="膳食名称">
          <el-col :span="11">
            <el-input v-model="curFood.foodname"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="膳食类别">
          <el-col :span="11">
            <el-input v-model="curFood.foodtype"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="膳食标签">
          <el-col :span="11">
            <el-input v-model="curFood.foodlabel"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="膳食价格">
          <el-col :span="11">
            <el-input v-model="curFood.foodprice"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="是否清真">
          <el-col :span="11">
            <el-select v-model="curFood.isMuslim">
              <el-option label="是" value="0"></el-option>
              <el-option label="否" value="1"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="供应星期">
          <el-col :span="11">
            <el-select v-model="curFood.supplyDate">
              <el-option v-for="weekday in weekdays" :key="weekday.value" :label="weekday.label" :value="weekday.value"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="供应类型">
          <el-col :span="11">
            <el-select v-model="curFood.supplyType">
              <el-option label="早餐" value="1"></el-option>
              <el-option label="午餐" value="2"></el-option>
              <el-option label="晚餐" value="3"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <el-button @click="optOne()">{{buttonOpt}}</el-button>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import http from '@/axios/http';
import qs from "qs";

// 显示/隐藏列表视图
let showList = ref(true);

// 存放膳食数据集合
let foodList = ref([]);

// 报错提示
let errorMessage = ref("");

// 模糊查询绑定的 膳食名称
let queryFoodName = ref("");

// 对话框显示控制
let foodDialog = ref(false);

// 膳食信息，或者编辑已有膳食的 绑定数据
let curFood = ref({});

// 登记、修改膳食信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = ref("");
let buttonOpt = ref("");

// 对话框操作类型：1：添加 2：编辑
let dialogOptType = ref(1);

// 星期选项
const weekdays = ref([
  { label: "星期一", value: "星期一" },
  { label: "星期二", value: "星期二" },
  { label: "星期三", value: "星期三" },
  { label: "星期四", value: "星期四" },
  { label: "星期五", value: "星期五" },
  { label: "星期六", value: "星期六" },
  { label: "星期日", value: "星期日" },
]);

// 选中的星期
const selectedWeekday = ref('');

// 分页相关
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list: []
});

// 初始化页面
onMounted(() => {
  init();
});

// 初始化方法
function init() {
  pageContains.value = {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    list: []
  };
  getAllFoods();
}

// 查询所有膳食信息
function getAllFoods() {
  let params = {
    pageNum: pageContains.value.pageNum || 1,
    pageSize: pageContains.value.pageSize || 10
  };
  http.post('/lyy/get_all_foods', params).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          pageContains.value = {
            ...result.data,
            pageNum: result.data.pageNum || 1,
            pageSize: result.data.pageSize || 10,
            total: result.data.total || 0,
            list: result.data.list || []
          };
          foodList.value = pageContains.value.list;
          showList.value = true;
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 根据膳食名称和星期查询膳食信息
function queryByFoodName() {
  let param = {
    foodname: queryFoodName.value,
    supplyDate: selectedWeekday.value
  };
  http.post('/lyy/get_foods_by_name', param).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          foodList.value = result.data;
          showList.value = false;
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 显示膳食登记对话框
function showFoodDialog() {
  dialogTitle.value = "膳食登记";
  buttonOpt.value = "录入";
  foodDialog.value = true;
  dialogOptType.value = 1; // 设置当前操作类型标志是 录入
  curFood.value = {}; // 清空表单数据
}

// 关闭膳食信息对话框
function closeFoodDialog() {
  foodDialog.value = false;
}

// 添加一条膳食记录
function addFood() {
  let param = curFood.value;
  http.post('/lyy/add_one_food', param).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          closeFoodDialog();
          // 只刷新当前页面，不跳转显示全部
          if (showList.value) {
            getAllFoods();
          } else {
            queryByFoodName();
          }
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 显示编辑对话框
function showEditDialog(foodId) {
  getFoodInfo(foodId);
  foodDialog.value = true;
  dialogTitle.value = "编辑膳食信息";
  buttonOpt.value = "修改";
  dialogOptType.value = 2; // 设置当前操作类型标志是 修改
}

// 根据ID查询膳食信息
function getFoodInfo(foodId) {
  let param = {
    id: foodId
  };
  http.post('/lyy/get_food_by_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          curFood.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 删除膳食记录
function removeOne(foodId) {
  let param = {
    id: foodId
  };
  http.post('/lyy/remove_food_by_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          // 只刷新当前页面，不跳转显示全部
          if (showList.value) {
            getAllFoods();
          } else {
            queryByFoodName();
          }
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 修改膳食记录
function editFood() {
  let param = curFood.value;
  http.post('/lyy/modify_food_by_id', param).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          closeFoodDialog();
          // 只刷新当前页面，不跳转显示全部
          if (showList.value) {
            getAllFoods();
          } else {
            queryByFoodName();
          }
        } else {
          errorMessage.value = result.error;
        }
      }
  );
}

// 操作方法
function optOne() {
  if (dialogOptType.value === 1) {
    addFood();
  } else if (dialogOptType.value === 2) {
    editFood();
  }
}

// 星期选择按钮点击
function selectWeekday(weekday) {
  selectedWeekday.value = weekday;
  showList.value = false;
  if (weekday !== '') {
    queryByFoodName();
  }
}

// 选择全部
function selectAll() {
  selectedWeekday.value = '';
  queryFoodName.value = '';
  showList.value = true;
  getAllFoods();
}

// 计算属性 - 分类显示
const morningFoods = computed(() => {
  return foodList.value.filter(food => food.supplyType === '1').slice(0, 8);
});

const noonFoods = computed(() => {
  return foodList.value.filter(food => food.supplyType === '2').slice(0, 8);
});

const eveningFoods = computed(() => {
  return foodList.value.filter(food => food.supplyType === '3').slice(0, 8);
});

// 新增特定类型膳食
function addMorningFood() {
  curFood.value.supplyType = '1';
  showFoodDialog();
}

function addNoonFood() {
  curFood.value.supplyType = '2';
  showFoodDialog();
}

function addEveningFood() {
  curFood.value.supplyType = '3';
  showFoodDialog();
}

// 分页处理
const handlePageChange = (pageNum1) => {
  if (pageContains.value) {
    pageContains.value.pageNum = pageNum1;
    getAllFoods();
  }
};

const handleSizeChange = (pageSize1) => {
  if (pageContains.value) {
    pageContains.value.pageSize = pageSize1;
    getAllFoods();
  }
};
</script>

<style scoped>
.box-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>